/**
 * 
 */
package net.streamming;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author linzq
 * 
 */
public class InputStreamR {
    public static void main(String[] args) {
        String dir = InputStreamR.class.getResource(".").getPath();
        File file = new File(dir + "a.txt");
        System.out.println(file.getAbsolutePath());
        read2(file);
    }

    public static void read1(File file) {
        try {
            FileInputStream input = new FileInputStream(file);
            byte[] bytes = new byte[100];
            for (int i = 0; i < bytes.length; i++) {
                int b = input.read();// read()方法读取一个字节后返回一个0至255之间的无符号整数
                if (b == -1)
                    break;
                bytes[i] = (byte) b;// 字节数组（bytes）是有符号的，在将赋值到bytes[i]时会被转换成-128至127的整数
            }
            for (int i = 0; i < bytes.length; i++) {
                int b = bytes[i];
                int j = b >= 0 ? b : 256 + b;// 读取字节数组时将有符号整数转换为无符号整数
                System.out.println(j);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void read2(File file) {
        try {
            FileInputStream input = new FileInputStream(file);

            int bytesReaded = 0;
            int bytesToRead = 1024;
            byte[] bytes = new byte[bytesToRead];
            int result = 0;
            while (bytesReaded < bytesToRead) {
                // 返回已经读取的字节长度，如果返回-1表示已经到达文件末尾
                result = input.read(bytes, bytesReaded, bytesToRead - bytesReaded);
                if(result==-1){
                    break;
                }
                bytesReaded+=result;
            }
            for (int i = 0; i < bytes.length; i++) {
                int b = bytes[i];
                int j = b >= 0 ? b : 256 + b;// 读取字节数组时将有符号整数转换为无符号整数
                System.out.println(j);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
